package com.dcy.daily.common.utils;

import com.dcy.daily.common.enums.ResponseCodeEnum;
import com.dcy.daily.common.exception.ValidateException;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * json格式化工具类
 */
public class JsonFormatUtils {

    private static ObjectMapper om = SpringUtil.getBean(ObjectMapper.class);

    public static ObjectMapper getOm(){
        return om.copy();
    }

    /**
     * 转换为 JSON 字符串,包含空值
     *
     * @param obj
     * @return
     */
    public static String obj2json(Object obj) {
        try{
            ObjectMapper tempOm = om.copy();
            tempOm.setSerializationInclusion(JsonInclude.Include.ALWAYS);
            return tempOm.writeValueAsString(obj);
        }catch (Exception e){
            throw new ValidateException(ResponseCodeEnum.OBJECT_TO_JSON_ERROR.getCode(),e);
        }
    }

    /**
     * 转换为 JSON 字符串，忽略null
     *
     * @param obj
     * @return
     */
    public static String obj2jsonIgnoreNull(Object obj) {
        try{
            return om.writeValueAsString(obj);
        }catch (Exception e){
            throw new ValidateException(ResponseCodeEnum.OBJECT_TO_JSON_ERROR.getCode(),e);
        }
    }

    /**
     * 转换为 JSON 字符串，忽略 null 和 ”“
     *
     * @param obj
     * @return
     */
    public static String obj2jsonIgnoreEmpty(Object obj) {
        try{
            ObjectMapper tempOm = om.copy();
            tempOm.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
            return tempOm.writeValueAsString(obj);
        }catch (Exception e){
            throw new ValidateException(ResponseCodeEnum.OBJECT_TO_JSON_ERROR.getCode(),e);
        }
    }

    /**
     * 转换为 JavaBean
     *
     * @param jsonString
     * @param clazz
     * @return
     */
    public static <T> T json2pojo(String jsonString, Class<T> clazz) {
        try{
            return om.readValue(jsonString, clazz);
        }catch (Exception e){
            throw new ValidateException(ResponseCodeEnum.OBJECT_TO_POJO_ERROR.getCode(),e);
        }
    }

    /**
     * 转换为 JavaBean
     *
     * @param jsonString
     * @param clazz
     * @return
     */
    public static <T> T json2pojoAlways(String jsonString, Class<T> clazz) {
        try{
            ObjectMapper tempOm = om.copy();
            tempOm.setSerializationInclusion(JsonInclude.Include.ALWAYS);
            return tempOm.readValue(jsonString, clazz);
        }catch (Exception e){
            throw new ValidateException(ResponseCodeEnum.OBJECT_TO_POJO_ERROR.getCode(),e);
        }
    }

    /**
     * 下划线驼峰转换
     * @param jsonString
     * @param clazz
     * @param flag true 转换
     * @param <T>
     * @return
     */
    public static <T> T json2pojo(String jsonString, Class<T> clazz,boolean flag) {
        try{
            if(flag){
                ObjectMapper tempOm = om.copy();
                tempOm.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
                return tempOm.readValue(jsonString, clazz);
            }else{
                return om.readValue(jsonString, clazz);
            }
        }catch (Exception e){
            throw new ValidateException(ResponseCodeEnum.JSON_TO_POJO_ERROR.getCode(),e);
        }
    }

    /**
     * 下划线驼峰转换
     * @param jsonString
     * @param clazz
     * @param flag true 转换
     * @param <T>
     * @return
     */
    public static <T> T json2pojoAlways(String jsonString, Class<T> clazz,boolean flag) {
        try{
            if(flag){
                ObjectMapper tempOm = om.copy();
                tempOm.setSerializationInclusion(JsonInclude.Include.ALWAYS);
                tempOm.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
                return tempOm.readValue(jsonString, clazz);
            }else{
                return om.readValue(jsonString, clazz);
            }
        }catch (Exception e){
            throw new ValidateException(ResponseCodeEnum.JSON_TO_POJO_ERROR.getCode(),e);
        }
    }

    /**
     * 字符串转换为 Map<String, Object>
     *
     * @param jsonString
     * @return
     */
    public static Map<String, Object> json2map(String jsonString) {
        try{
            return om.readValue(jsonString, Map.class);
        }catch (Exception e){
            throw new ValidateException(ResponseCodeEnum.JSON_TO_MAP_ERROR.getCode(),e);
        }
    }

    /**
     * 字符串转换为 Map<String, T>
     */
    public static <T> Map<String,T> json2map(String jsonArrayStr, Class<T> clazz){
        JavaType javaType = getCollectionType(HashMap.class,String.class,clazz);
        Map<String,T> map = null;
        try {
            map = (Map<String,T>) om.readValue(jsonArrayStr, javaType);
        } catch (Exception e) {
            throw new ValidateException(ResponseCodeEnum.JSON_TO_MAP_ERROR.getCode(),e);
        }
        return map;
    }

    /**
     * 深度转换 JSON 成 Map
     *
     * @param json
     * @return
     */
    public static Map<String, Object> json2mapDeeply(String json){
        return json2MapRecursion(json, om);
    }

    /**
     * 把 JSON 解析成 List，如果 List 内部的元素存在 jsonString，继续解析
     *
     * @param json
     * @param mapper 解析工具
     * @return
     */
    private static List<Object> json2ListRecursion(String json, ObjectMapper mapper){
        if (json == null) {
            return null;
        }
        List<Object> list = null;
        try {
            list = mapper.readValue(json, List.class);
        } catch (Exception e) {
            throw new ValidateException(ResponseCodeEnum.JSON_TO_LIST_ERROR.getCode(),e);
        }
        for (Object obj : list) {
            if (obj != null && obj instanceof String) {
                String str = (String) obj;
                if (str.startsWith("[")) {
                    obj = json2ListRecursion(str, mapper);
                } else if (obj.toString().startsWith("{")) {
                    obj = json2MapRecursion(str, mapper);
                }
            }
        }
        return list;
    }

    /**
     * 把 JSON 解析成 Map，如果 Map 内部的 Value 存在 jsonString，继续解析
     *
     * @param json
     * @param mapper
     * @return
     */
    private static Map<String, Object> json2MapRecursion(String json, ObjectMapper mapper) {
        if (json == null) {
            return null;
        }
        Map<String, Object> map = null;
        try {
            map = mapper.readValue(json, Map.class);
        } catch (Exception e) {
            throw new ValidateException(ResponseCodeEnum.JSON_TO_MAP_ERROR.getCode(),e);
        }
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            Object obj = entry.getValue();
            if (obj != null && obj instanceof String) {
                String str = ((String) obj);

                if (str.startsWith("[")) {
                    List<?> list = json2ListRecursion(str, mapper);
                    map.put(entry.getKey(), list);
                } else if (str.startsWith("{")) {
                    Map<String, Object> mapRecursion = json2MapRecursion(str, mapper);
                    map.put(entry.getKey(), mapRecursion);
                }
            }
        }

        return map;
    }

    /**
     * 将 JSON 数组转换为集合
     *
     * @param jsonArrayStr
     * @param clazz
     * @return
     */
    public static <T> List<T> json2list(String jsonArrayStr, Class<T> clazz){
        JavaType javaType = getCollectionType(ArrayList.class, clazz);
        List<T> list = null;
        try {
            list = (List<T>) om.readValue(jsonArrayStr, javaType);
        } catch (Exception e) {
            throw new ValidateException(ResponseCodeEnum.JSON_TO_LIST_ERROR.getCode(),e);
        }
        return list;
    }

    /**
     * 划线驼峰转换
     * 将 JSON 数组转换为集合
     * @param jsonArrayStr
     * @param clazz
     * @param flag true 转换
     * @param <T>
     * @return
     */
    public static <T> List<T> json2list(String jsonArrayStr, Class<T> clazz,boolean flag){
        JavaType javaType = getCollectionType(ArrayList.class, clazz);
        List<T> list;
        try {
            if (flag) {
                ObjectMapper tempOm = om.copy();
                tempOm.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
                list = (List<T>) tempOm.readValue(jsonArrayStr, javaType);
            } else {
                list = (List<T>) om.readValue(jsonArrayStr, javaType);
            }
        }catch (Exception e){
            throw new ValidateException(ResponseCodeEnum.JSON_TO_LIST_ERROR.getCode(),e);
        }
        return list;
    }


    /**
     * 获取泛型的 Collection Type
     *
     * @param collectionClass 泛型的Collection
     * @param elementClasses  元素类
     * @return JavaType Java类型
     * @since 1.0
     */
    public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
        return om.getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }

    /**
     * 将 Map 转换为 JavaBean
     *
     * @param map
     * @param clazz
     * @return
     */
    public static <T> T map2pojo(Map map, Class<T> clazz) {
        return om.convertValue(map, clazz);
    }

    /**
     * 将 Map 转换为 JSON
     *
     * @param map
     * @return
     */
    public static String mapToJson(Map map) {
        try {
            return om.writeValueAsString(map);
        } catch (Exception e) {
            throw new ValidateException(ResponseCodeEnum.MAP_TO_JSON_ERROR.getCode(),e);
        }
    }

    /**
     * 将 JSON 对象转换为 JavaBean
     *
     * @param obj
     * @param clazz
     * @return
     */
    public static <T> T obj2pojo(Object obj, Class<T> clazz) {
        try {
            return om.convertValue(obj, clazz);
        } catch (Exception e) {
            throw new ValidateException(ResponseCodeEnum.OBJECT_TO_JSON_ERROR.getCode(),e);
        }

    }

    /**
     * 将 JSON 对象转换为 JavaBean
     *
     * @param obj
     * @param clazz
     * @return
     */
    public static <T> T obj2pojoAlways(Object obj, Class<T> clazz) {
        try {
            ObjectMapper tempOm = om.copy();
            tempOm.setSerializationInclusion(JsonInclude.Include.ALWAYS);
            return om.convertValue(obj, clazz);
        } catch (Exception e) {
            throw new ValidateException(ResponseCodeEnum.OBJECT_TO_JSON_ERROR.getCode(),e);
        }

    }

    /**
     * 获取JSON字符串中的字段值
     * @param json
     * @param field 字段名
     * @return
     */
    public static String jsonGetField(String json,String field){
        try {
            JsonNode jsonNode = om.readTree(json);
            JsonNode returnStr = jsonNode.get(field);
            if(StringUtils.isNotNull(returnStr)){
                return returnStr.asText();
            }
            return null;
        }catch (Exception e){
            throw new ValidateException(ResponseCodeEnum.JSON_GET_FIELD_ERROR.getCode(),e);
        }
    }

    /**
     * 获取JSON字符串对象并转为String
     * @param json
     * @param field 字段名
     * @return
     */
    public static String jsonGetObject2Str(String json,String field){
        try {
            JsonNode jsonNode = om.readTree(json);
            JsonNode returnStr = jsonNode.get(field);
            if(StringUtils.isNotNull(returnStr)){
                return returnStr.toPrettyString();
            }
            return null;
        }catch (Exception e){
            throw new ValidateException(ResponseCodeEnum.JSON_GET_FIELD_ERROR.getCode(),e);
        }
    }

    /**
     * 获取JSON嵌套字符串中的字段值
     * @param json
     * @param field 字段名
     * @param index 字段嵌套数组的角标值; ==-1 时，表示是非数组形式；只处理一层嵌套
     * @return
     */
    public static String jsonGetField(String json,String field,int index,String childField){
        String returnStr;
        try {
            JsonNode jsonNode = om.readTree(json);
            JsonNode value = jsonNode.get(field);
            if(index <= -1){
                JsonNode indexValue = value.get(childField);
                returnStr = indexValue.asText();
            }else{
                JsonNode child = value.get(index);
                returnStr = child.get(childField).asText();
            }
            return returnStr;
        }catch (Exception e){
            throw new ValidateException(ResponseCodeEnum.JSON_GET_FIELD_ERROR.getCode(),e);
        }
    }

    public static byte[] objectAsBytes(Object o){
        try{
            return om.writeValueAsBytes(o);
        }catch (Exception e){
            throw new ValidateException(ResponseCodeEnum.OBJECT_TO_BYTE_ERROR.getCode(),e);
        }
    }
}
